<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>webSocket - dome</title>
</head>
<body>
	<input type="text" placeholder="输入消息" />
	<button>发消息</button>
	
	<script>
		const urlParams = new URLSearchParams(window.location.search);
		const userId = urlParams.get('userId') || 'defaultUser';

		const ws = new WebSocket('ws://localhost:8080');
		ws.onopen = function() {
			console.log('WebSocket连接已打开, 用户ID:', userId);
			ws.send(JSON.stringify({userId, message: '连接已建立'}));
		};

		ws.onmessage = function(event) {
			const {userId:id,message} = JSON.parse(event.data);
			console.log(userId,id,userId == id);
			if(userId != id){
				console.log('用户', id + '上线!');
			}
		};

		ws.onclose = function() {
			console.log('WebSocket连接已关闭');
		};
		ws.onerror = function(error) {
			console.error('WebSocket error:', error);
		};

		const input = document.querySelector('input');

		document.querySelector('button').addEventListener('click', function() {
			if (!input.value) {
				alert('请输入消息');
				return;
			};
			const message = userId+' - '+input.value + ' - ' + new Date().toLocaleString();
			console.log('我:', message);
			ws.send(JSON.stringify({userId, message}));
		});
		window.addEventListener('beforeunload', function() {
			ws.close();
		});
	</script>
</body>
</html>